from django import forms
from django.core.exceptions import ValidationError

from app01 import models
from app01.models import UserInfo, PrettyNum
from app01.utils.bootstrtap import BootStrapModelForm, BootStrapForm
from app01.utils.encrypt import md5


class AdminModelForm(BootStrapModelForm):
    # 创建一个重复输入密码的字段
    confirm_password = forms.CharField(
        label="确认密码",
        #                          密码验证不一致不会清空
        widget=forms.PasswordInput(render_value=True),
    )


    class Meta:
        model = models.Admin
        fields = ['username', 'password', 'confirm_password']
        widgets = {
            #                             密码验证不一致不会清空
            'password': forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        # 密码md5加密
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

    # 钩子方法 验证两次密码是否一致
    def clean_confirm_password(self):
        # 导入报错模块
        from django.core.exceptions import ValidationError
        pwd = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))
        if pwd != confirm:
            raise ValidationError("密码不一致!")
        return confirm
class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = models.Admin
        fields = ['username']
class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        #                          密码验证不一致不会清空
        widget=forms.PasswordInput(render_value=True),
    )

    class Meta:
        model = models.Admin
        fields = ['password', 'confirm_password']
        widgets = {
            #                             密码验证不一致不会清空
            'password': forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        # 密码md5加密
        pwd = self.cleaned_data.get('password')
        md5_pwd = md5(pwd)
        #                                    去数据库校验当前密码和新输入的密码是否一致
        exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
        if exists:
            raise ValidationError("密码不能与之前的密码一致")
        return md5_pwd

    # 钩子方法 验证两次密码是否一致
    def clean_confirm_password(self):
        # 导入报错模块
        from django.core.exceptions import ValidationError
        pwd = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))
        if pwd != confirm:
            raise ValidationError("密码不一致!")
        return confirm
class UserModelForm(BootStrapModelForm):
    # 可以对属性进行重写
    # create_time = DateField(editable=True)
    class Meta:
        model = UserInfo
        fields = ['name',
                  'password',
                  'age',
                  'account',
                  'gender',
                  'create_time',
                  'depart',
                  ]
class PrettyModelForm(BootStrapModelForm):
    # 正则表达式校验 验证方式一
    # mobile = forms.CharField(
    #     label="手机号",
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],
    # )
    class Meta:
        model = PrettyNum
        # 数据库字段 选择
        fields = ['mobile', 'price', 'level', 'status']
        # 自动关联所有的字段
        # fields = "__all__"
        # 下列语法是排除字段
        # exclude = ['level', '']

    # 验证方式二 钩子方法 前缀clean_字段名
    def clean_mobile(self):
        # 用户传入的数据
        mobile = self.cleaned_data['mobile']
        # 查找输入的字段是否存在 存在为True 不存在为F
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=mobile).exists()
        # 验证不通过
        if exists:
            raise ValidationError("号码已存在不能新建")
        if len(mobile) != 11:
            raise ValidationError("长度不对")
        return mobile

    # 重新定义修改modelform
class PrettyEditModelForm(BootStrapModelForm):
    # 正则表达式校验 验证方式一
    # 重新定义 禁止该字段进行修改
    # mobile = forms.CharField(
    #     # disabled=True,
    #     label="手机号",
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误'), ],
    # )
    class Meta:
        model = PrettyNum
        # 数据库字段 选择
        fields = ['mobile', 'price', 'level', 'status']

    def clean_mobile(self):
        # 当前编辑的数据库所在的ID
        # print(self.instance.pk)
        # 用户传入的数据
        mobile = self.cleaned_data['mobile']
        # 查找输入的字段是否存在 存在为True 不存在为F  exclude(id=self.instance.pk)排除ID等于自己
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=mobile).exists()

        return mobile
class LoginForm(BootStrapForm):
    """登录注册校验功能第一种写法"""
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        # 默认不能为空
        required=True
    )
    password = forms.CharField(
        label="密码",
        #                          输入错误不清空
        widget=forms.PasswordInput(render_value=True),
        required=True,
    )
    code = forms.CharField(
        label="验证码",
        #                          输入错误不清空
        widget=forms.PasswordInput,
        required=True,
    )
    # 钩子方法 获取输入的密码进行MD5加密然后返回
    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)
class LoginModelForm(BootStrapModelForm):
    """登录注册校验功能第二种写法"""

    class Meta:
        model = models.Admin
        fields = ['username', 'password']



class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = ['level', 'title', 'detail', 'user']